package com.example.redis.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Roger
 * @since 2021/6/19
 */
@Slf4j
@Service
public class RedisCommonService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * lua脚本练习
     */
    public void luaSwap(String vuale){
        String lua="local current = redis.call('GET', KEYS[1])\n" +
                "if current == ARGV[1]\n" +
                "  then redis.call('SET', KEYS[1], ARGV[2])\n" +
                "  return true\n" +
                "end\n" +
                "return false";

        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        //设置脚本
        redisScript.setScriptText(lua);
        redisScript.setResultType(Boolean.class);
        String key = "luaSwap";

        redisTemplate.delete(key);
        redisTemplate.opsForValue().set(key, "hahaha");
        String s = redisTemplate.opsForValue().get(key);
        log.info(s);

        redisTemplate.execute(redisScript, Collections.singletonList(key), vuale, "修改了");
        s = redisTemplate.opsForValue().get(key);
        log.info(s);

    }

    /**
     * Pipeline 练习
     *
     * @return
     */
    public Map<String, Object> testPipeline() {

        Long start = System.currentTimeMillis();
        List List = redisTemplate.executePipelined(new RedisCallback<Long>() {
            @Nullable
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                for (int i = 1000001; i < 1001000; i++) {
                    String key = "pipeline_" + i;
                    String value = "value_" + i;
                    connection.set(key.getBytes(), value.getBytes());
                }
                return null;
            }
        });

        Long end = System.currentTimeMillis();
        System.out.println("Pipeline插入1000000条记录耗时：" + (end - start) + "毫秒。");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        return map;
    }

    public Long deleteKey(String key){
        Set<String> keys = redisTemplate.keys(key+"*");
        Long num = redisTemplate.delete(keys);
        return num;
    }


}
